//
//  NSURLSessionViewController.swift
//  swift各类控件集锦
//
//  Created by iosdev1 on 2017/5/16.
//  Copyright © 2017年 zyy. All rights reserved.
//

import UIKit

class NSURLSessionViewController: ZyBaseViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
//        self.GET1()
//        self.POST()

        ZyNetWork.httpRequestTask(method: HTTPRequestMethod.POST, url: "http://120.25.226.186:32812/login", parameters: "username=520it&pwd=520it&type=JSON", error: true, SuccessClosure: { (data:Any) in
            echo(data: "\(data)")
        }) { (error) in
            echo(data: "\(error)")
        }

//        ZyNetWork.httpRequestTask(method: HTTPRequestMethod.GET, url: "https://b2b.i.jkbs365.com/client/info?access-token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiIxNDYzMiIsImV4cCI6MTgxMjI2MDIxNX0.1DuUHGhLOuhN0coK8AOG4yqb1hLBQ07J935GaVq7xjg&app_id=30&client=10&client_id=3960", parameters: "", error: true, SuccessClosure: { (data:Any) in
//            echo(data: "\(data)")
//        }) { (error) in
//            echo(data: "\(error)")
//        }
    }

    func GET1()
    {
        //对请求路径的说明
        //http://120.25.226.186:32812/login?username=520it&pwd=520&type=JSON
        //协议头+主机地址+接口名称+？+参数1&参数2&参数3
        //协议头(http://)+主机地址(120.25.226.186:32812)+接口名称(login)+？+参数1(username=520it)&参数2(pwd=520)&参数3(type=JSON)
        //GET请求，直接把请求参数跟在URL的后面以？隔开，多个参数之间以&符号拼接
        //1.确定请求路径
        let url: NSURL = NSURL(string: "https://b2b.i.jkbs365.com/client/info?access-token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiIxNDYzMiIsImV4cCI6MTgxMjI2MDIxNX0.1DuUHGhLOuhN0coK8AOG4yqb1hLBQ07J935GaVq7xjg&app_id=30&client=10&client_id=3960")!
        //2.创建请求对象
        //请求对象内部默认已经包含了请求头和请求方法（GET）
        let request:NSURLRequest = NSURLRequest(url: url as URL)
        //3.获得会话对象
        let session: URLSession = URLSession.shared
        //4.根据会话对象创建一个Task(发送请求）
        /*
         第一个参数：请求对象
         第二个参数：completionHandler回调（请求完成【成功|失败】的回调）
         data：响应体信息（期望的数据）
         response：响应头信息，主要是对服务器端的描述
         error：错误信息，如果请求失败，则error有值
         */
        let dataTask: URLSessionDataTask = session.dataTask(with: request as URLRequest) { (data, response, error) in
            if(error == nil){
                //6.解析服务器返回的数据
                
                //说明：（此处返回的数据是JSON格式的，因此使用NSJSONSerialization进行反序列化处理）
                var dict:Any? = nil
                do {
                    dict  = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.init(rawValue: 0))
                    echo(data: "\(String(describing: dict))")
//                    let dicData = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)
//                    echo(data: "\(dicData)")
                    
                } catch {
                }
            }
        }
        
//        let dataTask1 = session.dataTask(with: request as URLRequest) { (data, response, error) in
//            echo(data: "data:\(String(describing: data))\n response:\(String(describing: response))\n error:\(String(describing: error))")
//        }
//        echo(data: "\(dataTask1)")
        
        
        //5.执行任务
        dataTask.resume()
    }
    
    
    //发送POST请求NSURLSession
    
    func POST()
        
    {
        //对请求路径的说明
        //http://120.25.226.186:32812/login
        //协议头+主机地址+接口名称
        //协议头(http://)+主机地址(120.25.226.186:32812)+接口名称(login)
        //POST请求需要修改请求方法为POST，并把参数转换为二进制数据设置为请求体
        //1.创建会话对象
        let session: URLSession = URLSession.shared
        //2.根据会话对象创建task
        let url: NSURL = NSURL(string: "http://120.25.226.186:32812/login")!
//        let url: NSURL = NSURL(string: "https://api.qingpai365.com/auth/api-logout")!
        //3.创建可变的请求对象
        let request: NSMutableURLRequest = NSMutableURLRequest(url: url as URL)
        //4.修改请求方法为POST
        request.httpMethod = "POST"
        request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        //5.设置请求体
//        request.httpBody = "mobile=15168290517&captcha_id=44&captcha=999455".data(using: String.Encoding.utf8)
        request.httpBody = "username=520it&pwd=520it&type=JSON".data(using: String.Encoding.utf8)
        //6.根据会话对象创建一个Task(发送请求）
        /*
         第一个参数：请求对象
         第二个参数：completionHandler回调（请求完成【成功|失败】的回调）
         data：响应体信息（期望的数据）
         response：响应头信息，主要是对服务器端的描述
         error：错误信息，如果请求失败，则error有值
         */
        let dataTask: URLSessionDataTask = session.dataTask(with: request as URLRequest) { (data, response, error) in
            //if(error == nil){
            //8.解析数据
            //说明：（此处返回的数据是JSON格式的，因此使用NSJSONSerialization进行反序列化处理）
            var dict:NSDictionary? = nil
            do {
                let datass:Data = data!
                dict  = try JSONSerialization.jsonObject(with: datass, options: JSONSerialization.ReadingOptions.init(rawValue: 0)) as? NSDictionary
                
                let dicData = try JSONSerialization.jsonObject(with: datass, options: JSONSerialization.ReadingOptions.mutableContainers)
                echo(data: "\(dicData)")//返回可变容器，NSMutableDictionary或NSMutableArray。
                
                let dicData1 = try JSONSerialization.jsonObject(with: datass, options: JSONSerialization.ReadingOptions.mutableLeaves)
                echo(data: "\(dicData1)")//返回的JSON对象中字符串的值为NSMutableString
                
                let dicData2 = try JSONSerialization.jsonObject(with: datass, options: JSONSerialization.ReadingOptions.allowFragments)
                echo(data: "\(dicData2)")//允许JSON字符串最外层既不是NSArray也不是NSDictionary，但必须是有效的JSON Fragment。例如使用这个选项可以解析 @“123” 这样的字符串                
            } catch {
            }
            print("%@",dict as Any)
            //}
        }
        //5.执行任务
        dataTask.resume()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
